﻿using AppMachine.Domain.LogicCom.AppComs;
using AppMachine.EntityFrameworkCore.Repositories.LogicCom;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace AppMachine
{
    public class MainWindowViewModel:Prism.Mvvm.BindableBase
    {
        private Models.PrimDiModel _PrimDiModel = default;
        public Models.PrimDiModel PrimDiModel {
            get => _PrimDiModel;
            set { SetProperty(ref _PrimDiModel, value); }
        }

        public MainWindowViewModel() {
            this.PrimDiModel = new Models.PrimDiModel();
        }

        private CancellationTokenSource __CancellationTokenSource = new();
        public CancellationTokenSource CancellationTokenSource {
            get {

                lock (this.GetType()){
                    if (!this.__CancellationTokenSource.TryReset()) {
                        this.__CancellationTokenSource = new CancellationTokenSource();
                    }
                }

                return this.__CancellationTokenSource;
            }
        }

        public ICommand WaitIOStatusCommand => new DelegateCommand(() => {
            Task.Run(() => {
                try {
                    AppComRepository.GetInstance().GetByID<ComSwitchRO>("06").Wait(true, 5000, this.CancellationTokenSource.Token);
                } catch(Exception ex) { 
                
                }                
            });
        });

        public ICommand WaitIOListStatusCommand => new DelegateCommand(() => {
            Task.Run(() => {
                try {

                    ComSwitchRO tempComSwitchRO01 = AppComRepository.GetInstance().GetByID<ComSwitchRO>("06");
                    ComSwitchRO tempComSwitchRO02 = AppComRepository.GetInstance().GetByID<ComSwitchRO>("07");
                    ComSwitch.Wait(true,5000, this.CancellationTokenSource.Token, [tempComSwitchRO01,tempComSwitchRO02]);
                } catch (Exception ex) {

                }
            });
        });

        public ICommand WaitCancellCommand => new DelegateCommand(() => { 
            this.CancellationTokenSource.Cancel();
        });

        public ICommand TestExecutorCommand => new DelegateCommand(() => {
            Task.Run(() => {
                ComSwitchExecutor tempComSwitchExecutor = AppComRepository.GetInstance().GetByID<ComSwitchExecutor>("12");
                tempComSwitchExecutor?.Execute();
            });
        });


    }
}
